//
//  MeVC.m
//  FeiHuaJiaoYu
//
//  Created by 范智渊 on 2018/10/8.
//  Copyright © 2018 范智渊. All rights reserved.
//

#import "JMMeVC.h"
#import "LayoutView.h"

#import "JMPickerSelectionView.h"
#import "JMPickerSelectionModel.h"
#import "PaddingView.h"
#import "LayoutScrollView.h"
#import "CustomStackView.h"
#import "JMMeHeader.h"

#import "JMBankAccountController.h"
#import "JMChangeMyBankController.h"
#import "JMServiceController.h"
#import "JMSettingsController.h"
#import "JMMyFeedbackController.h"
#import "JMMeScoreView.h"
#import "JMCommonView.h"
#import "JMMeWarningPopupView.h"
#import "UIView+PopupProtocol.h"
#import "JMMeDateWarningPopupView.h"
@interface JMMeVC ()
/// 跟视图
@property(nonatomic, strong) UIStackView *rootStack;
@property(nonatomic, strong) LayoutScrollView *scrollView;
@property(nonatomic, strong) JMMeHeader *headerView;
@property(nonatomic, strong) UILabel *cloudunScore;
@property(nonatomic, strong) UILabel *ficoScore;
@property(nonatomic, strong) JMMeScoreView *fico;
@property(nonatomic, strong) JMMeScoreView *cloudun;
@property(nonatomic, strong) JMCommonView *commonView;
@property(nonatomic, strong) JMMeWarningPopupView *ficoWarningPopupView;
@property(nonatomic, strong) JMMeDateWarningPopupView *ficoDateWarningPopupView;
@property(nonatomic, strong) JMMeDateWarningPopupView *cloudunDateWarningPopupView;

@end

@implementation JMMeVC
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.rdv_tabBarController setTabBarHidden:NO animated:YES];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    delayOperation(0, ^{
        [self requestUserInfo];
        [self requestCRInfo];
        [self requestFAQInfo];
    });
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.rdv_tabBarController setTabBarHidden:YES animated:YES];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor colorWithHexString:@"#F7F7F5"];

    self.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    self.scrollView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
    self.TitleLabel.text = @"";
    [self setupViews];
}

- (void)setupViews {
    
    [self.rootStack addArrangedSubview:self.scrollView];
    
    self.headerView = [JMMeHeader new];
    [self.headerView.widthAnchor constraintEqualToConstant:kScreenWidth].active = YES;
    [self.scrollView.rootStack addContentView:self.headerView];
    self.scrollView.backgroundColor =WhiteColor();
    self.scrollView.bounces = NO;
    
    UILabel *miCredito = [UILabel new];
    miCredito.textColor = [UIColor colorWithHexString:@"#0F1511"];
    miCredito.font = [UIFont systemFontOfSize:16 weight: UIFontWeightMedium];
    miCredito.text = @"Mi crédito";
    [miCredito sizeToFit];
    @weakify(self);

    [self.scrollView.rootStack addContentView: [PaddingView initWithContentView:miCredito edgeInsets:(UIEdgeInsetsMake(47, 25, 15, 34))]];
    
    self.fico = [JMMeScoreView new];
    self.fico.titleLab.text = @"FICO Score";
    self.fico.scoreLab.text = @"";
    [self.scrollView.rootStack addContentView: [PaddingView initWithContentView:self.fico edgeInsets:(UIEdgeInsetsMake(20, 25, 0, 25))]];
    [self.fico.obenBtn tapAction:^(UIView *sender) {
        @strongify(self);
        [self openCreditUrl:@"1"];
    }];
    self.fico.alert.tag = 1;
    [self.fico.alert addTarget:self action:@selector(dateExpireAction:) forControlEvents:(UIControlEventTouchUpInside)];
    self.fico.superview.hidden = YES;
    [self.fico tapAction:^(UIView *sender) {
        @strongify(self);
        [self openCreditUrl:@"1"];
    }];
    
    self.cloudun = [JMMeScoreView new];
    self.cloudun.titleLab.text = @"Cloudun Score";
    self.cloudun.scoreLab.text = @"";
    [self.cloudun.obenBtn tapAction:^(UIView *sender) {
        @strongify(self);
        [self openCreditUrl:@"2"];
    }];
    self.cloudun.alert.tag = 2;
    [self.scrollView.rootStack addContentView: [PaddingView initWithContentView:self.cloudun edgeInsets:(UIEdgeInsetsMake(22, 25, 0, 25))]];
    [self.cloudun.alert addTarget:self action:@selector(dateExpireAction:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.cloudun.topaAlert addTarget:self action:@selector(topAlertShow) forControlEvents:(UIControlEventTouchUpInside)];

    [self.cloudun tapAction:^(UIView *sender) {
        @strongify(self);
        [self openCreditUrl:@"2"];
    }];
    self.commonView = [JMCommonView new];
    self.commonView.cornerRadius = 12;
    self.commonView.faq.hidden = YES;
    WeakSelf
    self.commonView.clickAction = ^(NSInteger index) {
        if (index == 0) {
            [JMCommonMethod uploadStatistics:@"FAQ" actionType:@"Enter" parameters:nil];//@{@"productAndRanks":productAndRanks}

            [weakSelf viewCreditReport:@"3"];
        }else if (index == 1) {
            [JMCommonMethod uploadStatistics:@"CustomerService" actionType:@"Enter" parameters:nil];//@{@"productAndRanks":productAndRanks}

            JMServiceController *vc = [JMServiceController new];
            vc.type = 1;
            [weakSelf.navigationController pushViewController:vc animated:YES];
        }else if (index == 2) {
            [JMCommonMethod uploadStatistics:@"Complaint" actionType:@"Enter" parameters:nil];//@{@"productAndRanks":productAndRanks}

            JMServiceController *vc = [JMServiceController new];
            vc.type = 2;
            [weakSelf.navigationController pushViewController:vc animated:YES];
        }
    };
    [self.scrollView.rootStack addContentView:[PaddingView initWithContentView:self.commonView edgeInsets:(UIEdgeInsetsMake(12, 20, 0, 20))]];
    
    
    
    CustomStackView *listStack = [CustomStackView init:(UILayoutConstraintAxisVertical)];
    for(NSInteger i = 0; i < 3; i ++) {
        
        CustomStackView *rowStack = [CustomStackView init:(UILayoutConstraintAxisHorizontal)];
        rowStack.spacing = 12;
        rowStack.alignment = UIStackViewAlignmentCenter;
        
        UIImageView *icon = [UIImageView new];
        [icon.widthAnchor constraintEqualToConstant:20].active = YES;
        [icon.heightAnchor constraintEqualToConstant:20].active = YES;
        icon.contentMode = UIViewContentModeScaleAspectFill;
        [rowStack addArrangedSubview:icon];
        
        UILabel *title = [UILabel new];
        title.textColor = [UIColor colorWithHexString:@"#0F1511"];
        title.font = [UIFont systemFontOfSize:14];
        [rowStack addArrangedSubview:title];
        
        UIImageView *more = [UIImageView new];
        [more.widthAnchor constraintEqualToConstant:24].active = YES;
        [more.heightAnchor constraintEqualToConstant:24].active = YES;
        more.contentMode = UIViewContentModeScaleAspectFill;
        more.image = [UIImage imageNamed:@"Group 8782"];
        [more.widthAnchor constraintEqualToConstant:7].active = YES;
        [rowStack addArrangedSubview:more];
        
        [listStack addArrangedSubview:[[PaddingView initWithContentView:rowStack edgeInsets:(UIEdgeInsetsMake(20, 35, 20, 40))] then:^(PaddingView * _Nonnull view) {
            [view.widthAnchor constraintEqualToConstant:kScreenWidth].active = YES;
        }]];
                
        if (i == 0) {
            icon.image = [UIImage imageNamed:@"ICON／yin hang ka"];
            title.text = @"Cuenta bancaria";
            [rowStack.superview tapAction:^(UIView *sender) {
                JMBankAccountController *vc = [JMBankAccountController new];
                vc.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:vc animated:YES];
            }];
        }else if (i == 1) {
            icon.image = [UIImage imageNamed:@"Slice 6"];
            title.text = @"Política de privacidad";
            [rowStack.superview tapAction:^(UIView *sender) {
                [JMCommonMethod presentWebviewWithUrl:serviceUrlWith(loginPrivacyAgreement) andTitle:@"Política de privacidad"];
            }];
        }else if (i == 2) {
            icon.image = [UIImage imageNamed:@"ICON／she zhi"];
            title.text = @"Configurar";
            [rowStack.superview tapAction:^(UIView *sender) {
                JMSettingsController *vc = [JMSettingsController new];
                vc.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:vc animated:YES];
            }];
        }
    }
    
    [self.scrollView.rootStack addContentView: [PaddingView initWithContentView:listStack edgeInsets:(UIEdgeInsetsMake(0, 0, 0, 0))]];
 
}
-(void)topAlertShow{
    [self.ficoWarningPopupView popup: [UIApplication sharedApplication].keyWindow edgeInsets:(UIEdgeInsetsZero)];
}

- (void)dateExpireAction: (UIButton *)sender {
    if (sender.tag==1) {
        [self.ficoDateWarningPopupView popup:[UIApplication sharedApplication].keyWindow edgeInsets:(UIEdgeInsetsZero)];

    }else{
        [self.cloudunDateWarningPopupView popup:[UIApplication sharedApplication].keyWindow edgeInsets:(UIEdgeInsetsZero)];
    }
}

- (void)ficoWarningPopupViewConfirm:(UIButton *)sender {
    [self.ficoWarningPopupView dismissPopup];
    [self viewCreditReport: @"1"];
}


/// 查看信用报告
- (void)viewCreditReport:(NSString *)type {
    [self openCreditUrl:type];
}

#pragma mark - 网络请求
- (void)requestUserInfo {
    
    NSDictionary *dic = @{
        
    };
    [[JMBaseRequest sharedInstance] requestBasePost:BasePostRequestUrl(@"/api/user/baseInfo") params:dic success:^(NSDictionary * _Nullable dataDic, NSArray * _Nullable dataArray) {
        NSDictionary *data = (NSDictionary *)dataDic;
        if (data != nil) {
            

            NSString *nickName = data[@"realName"];
            double unused = [data[@"unused"] doubleValue];
            double repaymentTotalAmount = [data[@"repaymentTotalAmount"] doubleValue];
            NSString *phone = [NSString stringWithFormat:@"%@", data[@"phone"]];
            [JMProjectManager sharedJMProjectManager].loginUser.phone = [NSString stringWithFormat:@"%@", phone];
            dispatch_async(dispatch_get_main_queue(), ^{
               
                self.headerView.nickName.text = [NSString stringWithFormat:@"%@", phone];
                self.headerView.cuotaDisponible.text = @(unused).stringValue.moneyString;
                self.headerView.montoPorReembolsar.text = @(repaymentTotalAmount).stringValue.moneyString;
            });
        }
        
       
    } fail:^(NSString * _Nonnull errorMsg) {
      
    }];
}

- (void)requestUserScore {
    
    NSDictionary *dic = @{
        @"partnerId": @"2fec752cc5d9a2774911936cfb21dd39",
        @"orderNo": JMProjectManager.sharedJMProjectManager.loginUser.userId
    };
    [[JMBaseRequest sharedInstance] requestBasePost:BasePostRequestUrl(@"/api/third/cr/h5/getCRSource") params:dic success:^(NSDictionary * _Nullable dataDic, NSArray * _Nullable dataArray) {
        NSDictionary *data = (NSDictionary *)dataDic;
        if (data != nil) {
            
            BOOL ficoshow = [data[@"ficoshow"] boolValue];
            BOOL ficoInfoError = [data[@"ficoInfoError"] boolValue];
//            ficoInfoError = YES;
            NSInteger cloudunScore = -1;
            if (data[@"cloudunScore"] != nil) {
                cloudunScore = [data[@"cloudunScore"] integerValue];
            }
            NSInteger ficoScore = -1;
            if (data[@"ficoScore"] != nil) {
                ficoScore = [data[@"ficoScore"] integerValue];
            }
            
            double ficoExpireTime = [data[@"ficoExpireTime"] doubleValue];
            double cloudunExpireTime = [data[@"cloudunExpireTime"] doubleValue];
            
            
            NSDate *currentDate = [NSDate new];
            
            double currentDateInterval = [currentDate timeIntervalSince1970] * 1000;
            
            double ficoDif = ficoExpireTime - currentDateInterval;
            double cloudunDif = cloudunExpireTime - currentDateInterval;
            
            BOOL showFicoWarning = (ficoDif <= 7 * 24 * 60 * 60 * 1000);
            BOOL showCloudunWarning = (cloudunDif <= 7 * 24 * 60 * 60 * 1000);
            
            
            NSDateFormatter *dateFormatter = [NSDateFormatter new];
            dateFormatter.dateFormat = @"MM-dd-yyyy";
            
            NSString *saveDateString = [[NSUserDefaults standardUserDefaults] stringForKey: @"FicoInfoError"];
            if (saveDateString == nil) {
                saveDateString = @"";
            }
            
            NSString *currentDateString = [dateFormatter stringFromDate: currentDate];
            
            
            dispatch_async(dispatch_get_main_queue(), ^{
                self.fico.superview.hidden = !ficoshow;
                self.fico.scoreLab.text = [NSString stringWithFormat:@"%ld", ficoScore];
                self.fico.scoreLab.hidden = ficoScore == -1 ? YES : NO;
                self.fico.obenBtn.hidden = ficoScore == -1 ? NO : YES;
                self.fico.moreImageView.hidden = ficoScore == -1 ? YES : NO;
                self.fico.dateStack.hidden = ficoExpireTime>0 ? NO : YES;
                
                NSDate *ficoDate = [[NSDate alloc] initWithTimeIntervalSince1970:ficoExpireTime / 1000.0];
                self.fico.dateLab.text = [dateFormatter stringFromDate:ficoDate];
                self.fico.alert.superview.hidden = !showFicoWarning;
                
                self.cloudun.scoreLab.text = [NSString stringWithFormat:@"%ld", cloudunScore];
                self.cloudun.scoreLab.hidden = cloudunScore == -1 ? YES : NO;
                self.cloudun.obenBtn.hidden = cloudunScore == -1 ? NO : YES;
                self.cloudun.moreImageView.hidden = cloudunScore == -1 ? YES : NO;
                self.cloudun.dateStack.hidden = cloudunExpireTime>0 ? NO : YES;
                
                NSDate *cloudunDate = [[NSDate alloc] initWithTimeIntervalSince1970:cloudunExpireTime / 1000.0];
                self.cloudun.dateLab.text = [dateFormatter stringFromDate:cloudunDate];
                self.cloudun.alert.superview.hidden = !showCloudunWarning;
                
                if (![saveDateString isEqualToString: currentDateString] && ficoInfoError) {
                    
                    [[NSUserDefaults standardUserDefaults] setObject:currentDateString forKey:@"FicoInfoError"];
                    [self.ficoWarningPopupView popup: [UIApplication sharedApplication].keyWindow edgeInsets:(UIEdgeInsetsZero)];
                }
                if (ficoInfoError) {
                    self.fico.errorLab.text = @"*FICO Score ha sido pagado, no se ha generado ningún informe, por favor cambie su información personal para volver a aprobar";
                    self.fico.errorLab.hidden = NO;
                    self.fico.topaAlert.superview.hidden = NO;
                    self.fico.scoreLab.text = @"???";
                    self.fico.errorLab.textAlignment = 0;
                    self.fico.scoreLab.textColor = Hex_Str_COLOR(@"#FF5252");
                    self.fico.dateStack.hidden = NO;
                    self.fico.dateLab.hidden = YES;
                    self.fico.dateStack.hidden = YES;
                }
            });
        }

    } fail:^(NSString * _Nonnull errorMsg) {

    }];
}

- (void)requestCRInfo {
    
    NSDictionary *dic = @{
        @"partnerId": @"2fec752cc5d9a2774911936cfb21dd39",
        @"pageType": @(2).stringValue
    };
    [[JMBaseRequest sharedInstance] requestBasePost:BasePostRequestUrl(@"/api/common/isShowCREntrance") params:dic success:^(NSDictionary * _Nullable dataDic, NSArray * _Nullable dataArray) {
        
        BOOL result = (BOOL)dataDic;
        
        if (result) {
            [self requestUserScore];
        }

    } fail:^(NSString * _Nonnull errorMsg) {
    }];
}

- (void)requestFAQInfo {
    NSDictionary *dic = @{
    };
    [[JMBaseRequest sharedInstance] requestBasePost:BasePostRequestUrl(@"/api/faq/isShowFAQEntrance") params:dic success:^(NSDictionary * _Nullable dataDic, NSArray * _Nullable dataArray) {
        
        BOOL result = (BOOL)dataDic;
        
        if (result) {
            dispatch_async(dispatch_get_main_queue(), ^{
               
                self.commonView.faq.hidden = NO;
            });
        }
    } fail:^(NSString * _Nonnull errorMsg) {

    }];
}
#pragma mark - 懒加载
- (UIStackView *)rootStack {
    if (!_rootStack) {
        self.rootStack = [UIStackView new];
        _rootStack.alignment = UIStackViewAlignmentCenter;
        _rootStack.axis = UILayoutConstraintAxisVertical;
        _rootStack.translatesAutoresizingMaskIntoConstraints = NO;
        [self.view addSubview:_rootStack];
        [NSLayoutConstraint activateConstraints:@[
            [_rootStack.topAnchor constraintEqualToAnchor:self.view.topAnchor],
            [_rootStack.leftAnchor constraintEqualToAnchor:self.view.leftAnchor],
            [_rootStack.rightAnchor constraintEqualToAnchor:self.view.rightAnchor],
            [_rootStack.bottomAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.bottomAnchor constant: -49]
        ]];
    }
    return  _rootStack;
}
- (LayoutScrollView *)scrollView {
    if (!_scrollView) {
        self.scrollView = [LayoutScrollView new];
        _scrollView.rootStack.contentView.axis = UILayoutConstraintAxisVertical;
        [_scrollView.widthAnchor constraintEqualToConstant: kScreenWidth].active = YES;
        _scrollView.rootStack.layoutViewAlignment = LayoutViewAlignmentTop;
        _scrollView.contentInset = UIEdgeInsetsMake(36, 0, 0, 0);
        _scrollView.showsVerticalScrollIndicator = NO;
        _scrollView.rootStack.layoutViewAlignment = LayoutViewAlignmentTop;
    }
    return _scrollView;
}

- (JMMeWarningPopupView *)ficoWarningPopupView {
    if (!_ficoWarningPopupView) {
        self.ficoWarningPopupView = [JMMeWarningPopupView new];
        [_ficoWarningPopupView.widthAnchor constraintEqualToConstant:kScreenWidth - 20].active = YES;
        [_ficoWarningPopupView.confirm addTarget:self action:@selector(ficoWarningPopupViewConfirm:) forControlEvents:(UIControlEventTouchUpInside)];
    }
    return _ficoWarningPopupView;
}
- (JMMeDateWarningPopupView *)ficoDateWarningPopupView {
    if (!_ficoDateWarningPopupView) {
        self.ficoDateWarningPopupView = [JMMeDateWarningPopupView new];
        [_ficoDateWarningPopupView.widthAnchor constraintEqualToConstant:kScreenWidth].active = YES;
    }
    return _ficoDateWarningPopupView;
}
- (JMMeDateWarningPopupView *)cloudunDateWarningPopupView {
    if (!_cloudunDateWarningPopupView) {
        _cloudunDateWarningPopupView = [JMMeDateWarningPopupView new];
        _cloudunDateWarningPopupView.contentLab.text =  @"En general, las puntuaciones Cloudun no cambian mucho con el tiempo. Pero es importante tener en cuenta que su puntuación Cloudun se calcula cada vez que se solicita, ya sea por usted o por un prestamista. Y cada vez que se calcula, se actualiza la información que figura en su informe crediticio en ese momento. Por lo tanto, a medida que cambia la información de su informe de crédito, también puede cambiar su puntuación Cloudun.\nSe recomienda que proporcione un informe de crédito actualizado para que los prestamistas puedan evaluar su crédito con precisión.";
        [_cloudunDateWarningPopupView.widthAnchor constraintEqualToConstant:kScreenWidth].active = YES;
    }
    return _cloudunDateWarningPopupView;
}
@end
